<template>
  <div class="group-assistant-send">
    <!-- 步骤条 -->
    <el-steps
      class="group-send-steps"
      align-center
      :active="currentStep"
      :process-status="currentStepStatus"
      finish-status="success"
    >
      <el-step title="选择好友/群" icon="el-icon-s-check"></el-step>
      <el-step title="编辑推送" icon="el-icon-edit"></el-step>
      <!-- <el-step title="发送" icon="el-icon-s-promotion"></el-step> -->
    </el-steps>

    <!-- 好友筛选|内容编辑 -->
    <div class="group-send-content">
      <!-- 好友筛选页面 -->
      <div v-if="currentStep === 0" class="chose-friend">
        <el-tabs
          class="chose-friend-left scroll"
          type="border-card"
          v-model="activeTabName"
        >
          <el-tab-pane label="选择好友推送消息" name="choseFriends">
            <!-- 所在微信 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">所在微信</span>
              <el-select
                v-model="wechat2send"
                clearable
                placeholder="请选择"
                @change="queryInfoByWechatId"
              >
                <el-option
                  v-for="(wechat, index) in wechats"
                  :key="index"
                  :label="wechat.WeChatNick"
                  :value="wechat.WeChatId"
                  :disabled="!wechat.IsOnline || !wechat.IsLogined"
                ></el-option>
              </el-select>
            </div>
            <!-- 所在分组 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">所在分组</span>
              <el-select
                v-model="team2screen"
                clearable
                placeholder="请选择"
                disabled
              ></el-select>
            </div>
            <!-- 性别 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">性别</span>
              <el-select v-model="gender2screen" clearable placeholder="请选择">
                <el-option
                  v-for="(item, index) in gender"
                  :key="'gender' + index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
            <!-- 状态 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">状态</span>
              <el-select
                v-model="state2screen"
                clearable
                placeholder="请选择"
                disabled
              ></el-select>
            </div>
            <!-- 标签 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">标签</span>
              <el-radio-group v-model="lableRadio">
                <el-radio :label="'inclusion'">包含</el-radio>
                <el-radio :label="'exclude'">不包含</el-radio>
              </el-radio-group>
            </div>
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title"></span>
              <el-select
                v-model="labels2screen"
                multiple
                filterable
                :placeholder="wechat2send ? '请选择' : '请先选择微信'"
                :disabled="!wechat2send"
                collapse-tags
              >
                <el-option
                  v-for="(item, index) in groupSendLabels"
                  :key="'label' + index"
                  :label="item.LabelName"
                  :value="item.LabelId"
                ></el-option>
              </el-select>
            </div>
            <!-- 城市 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">城市</span>
              <el-radio-group v-model="cityRadio">
                <el-radio :label="'inclusion'">包含</el-radio>
                <el-radio :label="'exclude'">不包含</el-radio>
              </el-radio-group>
            </div>
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title"></span>
              <el-cascader
                v-model="cities"
                :options="chineseCities"
                :props="{ expandTrigger: 'hover', multiple: true }"
                :show-all-levels="false"
                @change="handleCityChange"
                filterable
                collapse-tags
              ></el-cascader>
            </div>
            <!-- 筛选|重置 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title"></span>
              <el-button type="primary" @click="screenFriends">筛选</el-button>
              <el-button type="info" @click="resetFilter">重置</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="选择群推送消息" name="choseRooms">
            <!-- 所在微信 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">所在微信</span>
              <el-select
                v-model="wechat2send2room"
                clearable
                placeholder="请选择"
                @change="queryInfoByWechatId"
              >
                <el-option
                  v-for="(wechat, index) in wechats"
                  :key="index"
                  :label="wechat.WeChatNick"
                  :value="wechat.WeChatId"
                  :disabled="!wechat.IsOnline || !wechat.IsLogined"
                ></el-option>
              </el-select>
            </div>
            <!-- 群名称 -->
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title">群名称</span>
              <el-input
                placeholder="请输入内容"
                v-model="room2screen"
                clearable
              ></el-input>
            </div>
            <div class="el-tab-pane-item">
              <span class="el-tab-pane-item-title"></span>
              <el-button type="primary" @click="screenRooms">筛选</el-button>
              <el-button type="info" @click="resetFilter">重置</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- 数据展示 -->
        <div class="chose-friend-right">
          <el-table
            :data="tableData[currentPage[activeTabName] - 1]"
            stripe
            border
            height="50"
            highlight-current-row
          >
            <el-table-column
              type="index"
              :index="indexMethod"
              label="序号"
              width="60px"
            ></el-table-column>
            <el-table-column
              label="昵称"
              :prop="
                activeTabName === 'choseFriends' ? 'FriendNick' : 'NickName'
              "
            ></el-table-column>
            <el-table-column
              v-if="activeTabName === 'choseFriends'"
              label="备注名"
              prop="Memo"
            ></el-table-column>
            <el-table-column
              v-if="activeTabName === 'choseFriends'"
              label="性别"
              prop="Gender"
              width="80px"
            ></el-table-column>
            <el-table-column
              v-if="activeTabName === 'choseFriends'"
              label="城市"
              prop="City"
            ></el-table-column>
            <el-table-column
              v-if="activeTabName === 'choseRooms'"
              label="群成员人数"
              width="100px"
            >
              <template slot-scope="scope">
                <span
                  v-if="activeTabName === 'choseRooms'"
                  v-text="scope.row.MemberList.length"
                ></span>
              </template>
            </el-table-column>
            <!-- 全选 -->
            <!-- <el-table-column type="selection" reserve-selection align="center" width="80px"></el-table-column> -->
            <el-table-column width="100px" align="center">
              <template slot="header">
                <el-button
                  size="mini"
                  style="padding: 5px"
                  type="primary"
                  @click="choseAllOfPage"
                  >全选本页</el-button
                >
              </template>
              <template slot-scope="scope">
                <input
                  type="checkbox"
                  :checked="computedCheckState(scope.row)"
                  @click="choseRow(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage[activeTabName]"
            :page-sizes="[15, 30, 45, 60]"
            :page-size="pageSize"
            :pager-count="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalNum"
          ></el-pagination>
        </div>
      </div>
      <!-- 内容编辑页面 -->
      <div v-else-if="currentStep === 1" class="set-send-content">
        <!-- 新增消息 -->
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="add-new-msg-btn"
          @click="showContentDialog = true"
          >新增消息</el-button
        >
        <!-- 消息内容展示 -->
        <el-table
          :data="contentData"
          style="width: 100%"
          height="60"
          border
          stripe
        >
          <el-table-column
            label="消息类型"
            prop="msgType"
            width="180"
          ></el-table-column>
          <el-table-column label="消息内容" prop="msgContent"></el-table-column>
          <el-table-column label="操作" width="220" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled="scope.$index === 0"
                @click="removeUp(scope.$index, scope.row)"
                >上移</el-button
              >
              <el-button
                size="mini"
                :disabled="scope.$index === contentData.length - 1"
                @click="removeDown(scope.$index, scope.row)"
                >下移</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="deleteContent(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 设置定时任务 -->
        <div class="set-time">
          <div class="broke-time" v-show="false">
            <span>间隔范围(秒)</span>
            <el-input-number
              size="small"
              v-model="minTime"
              controls-position="right"
              :min="1"
              :max="maxTime - 1"
              disabled
              style="margin: 0 5px"
            ></el-input-number>
            <span>-</span>
            <el-input-number
              size="small"
              v-model="maxTime"
              controls-position="right"
              :min="minTime + 1"
              :max="120"
              disabled
              style="margin: 0 5px"
            ></el-input-number>
          </div>
          <div class="broke-time">
            <span>群发开始时间</span>
            <el-radio-group v-model="timeRadio" style="margin-left: 10px">
              <el-radio :label="'rightNow'">立即开始</el-radio>
              <el-radio :label="'timing'">定时开始</el-radio>
              <el-date-picker
                v-model="refTime"
                type="datetime"
                placeholder="选择日期时间"
                clearable
                size="small"
                :disabled="timeRadio === 'rightNow'"
              ></el-date-picker>
            </el-radio-group>
          </div>
          <span>
            <i
              class="el-icon-warning"
              style="color: #e6a23c; font-size: 14px"
            ></i>
            选择时间间隔范围后，每一条消息完成发送后将会在范围内随机一个时间，按顺序推送下一条，
            随机间隔是为了避免微信判定非人工操作，请合理设置随机时间。
          </span>
        </div>
      </div>
    </div>

    <!-- 上一页|发送 -->
    <div class="group-send-operation">
      <el-button
        v-if="currentStep > 0"
        size="small"
        type="primary"
        icon="el-icon-arrow-left"
        @click="currentStep = 0"
        >上一步</el-button
      >
      <el-button
        v-if="currentStep === 0"
        size="small"
        type="primary"
        @click="sendNext('all')"
        >发送所有筛选结果的用户</el-button
      >
      <el-button
        v-if="currentStep === 0"
        size="small"
        type="primary"
        @click="sendNext('check')"
        >发送选择的用户</el-button
      >
      <el-button
        v-if="currentStep === 1"
        size="small"
        type="primary"
        @click="sureSend"
        >确认发送</el-button
      >
    </div>

    <!-- 编辑内容 -->
    <el-dialog
      class="el-dialog-content"
      title="新增消息"
      :visible.sync="showContentDialog"
    >
      <!-- 设置消息类型 -->
      <div class="set-type">
        <span class="set-type-span">消息类型</span>
        <el-select v-model="msgType" placeholder="请选择" size="small">
          <el-option
            v-for="type in msgTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          ></el-option>
        </el-select>
      </div>
      <!-- 设置内容 -->
      <div class="set-content">
        <!-- text -->
        <el-input
          v-if="msgType === 'Text'"
          type="textarea"
          placeholder="请输入内容"
          style="height: auto"
          v-model="msgContent"
          maxlength="500"
          show-word-limit
          :autosize="{ minRows: 6, maxRows: 8 }"
          resize="none"
        ></el-input>
        <!-- picture|video|voice -->
        <el-upload
          v-if="
            msgType === 'Picture' || msgType === 'Video' || msgType === 'Voice'
          "
          action="http://www.jjldkj.com:10089/fileUpload2020"
          list-type="picture-card"
          :class="{ hide: hideUpload }"
          :data="upData"
          :before-upload="beforeImageUpload"
          :on-change="handleImageChange"
          :on-success="handleImageSuccess"
          :on-error="handleImageError"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :multiple="false"
          :show-file-list="showFileList"
          :accept="
            msgType === 'Picture'
              ? '.jpg, .png, .jpeg'
              : msgType === 'Video'
              ? '.mp4'
              : '.mp3, .amr'
          "
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <!-- link -->
        <el-form
          class="we-app"
          v-if="msgType === 'Link'"
          :model="linkForm"
          :rules="linkRules"
          ref="linkDialog"
          label-width="110px"
        >
          <el-form-item
            :label="index"
            :prop="index"
            v-for="(link, index) in linkForm"
            :key="'link' + index"
          >
            <el-input
              v-model="linkForm[index]"
              :disabled="index === 'TypeStr'"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <!-- weapp -->
        <el-form
          class="we-app"
          v-if="msgType === 'WeApp'"
          :model="weapp"
          :rules="weappRules"
          ref="weappDialog"
          label-width="110px"
        >
          <el-form-item
            :label="index"
            :prop="index"
            v-for="(wa, index) in weapp"
            :key="'weapp' + index"
          >
            <el-input v-model="weapp[index]" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 提示 -->
      <div class="tips">
        <span v-if="msgType === 'Picture'" class="el-icon-info"
          >&nbsp;仅支持jpg/png文件，且不超过2MB</span
        >
        <span
          v-else-if="msgType === 'Video'"
          class="el-icon-info"
          style="margin: 10px"
          >&nbsp;仅支持10M以内的MP4文件</span
        >
        <span v-else-if="msgType === 'Voice'" class="el-icon-info"
          >&nbsp;仅支持mp3和微信的amr文件</span
        >
        <!-- <span v-else-if="msgType === 'WeApp'" class="el-icon-info">&nbsp;带 * 的是必填的</span> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="msgType === 'Link' || msgType === 'WeApp'"
          @click="resetForm(msgType)"
          >重 置</el-button
        >
        <el-button type="info" @click="showContentDialog = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="addContent(msgType)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 大图dialog -->
    <el-dialog v-show="false" :visible.sync="dialogVisible">
      <el-image
        style="width: 600px; height: 600px"
        :src="msgContent"
        fit="contain"
      ></el-image>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import chineseCities from '@/utils/city.json'

export default {
  name: 'GroupAssistantSend',
  data() {
    return {
      activeTabName: 'choseFriends', // 默认选择好友 choseRooms是选择群聊
      // 分页
      pageSize: 15, // 每页消息数
      currentPage: {
        choseFriends: 1,
        choseRooms: 1
      }, // 当前页

      showContentDialog: false, // 显示设置内容的dialog
      // 消息类型
      msgTypes: [
        {
          label: '文本消息',
          value: 'Text'
        },
        {
          label: '图片消息',
          value: "Picture"
        },
        {
          label: '语音消息',
          value: "Voice"
        },
        {
          label: '视频消息',
          value: "Video"
        },
        {
          label: '链接消息',
          value: "Link"
        },
        {
          label: '小程序消息',
          value: "WeApp"
        },
      ],
      canNotCreatedType: ['Voice', 'Link', 'WeApp'], // 不让创建的消息类型
      msgType: 'Text', // 正在创建的消息类型
      msgContent: '', // 正在创建的消息内容
      contentData: [], // 要发送的消息
      minTime: 1, // 发送间隔 最小间隔
      maxTime: 60, // 发送间隔 最大间隔
      timeRadio: 'rightNow', // 立即发送还是定时发送
      refTime: new Date().getTime(),
      // 文件上传相关
      hideUpload: false, // 隐藏文件上传按钮
      showFileList: true, // 显示文件列表
      imageUrl: '', // 图片url
      upData: { myfile: '', packageName: 'pc' }, // 上传文件data
      dialogVisible: false, // 显示大图

      weapp: {
        'AppId': 'wxe99ba6e7fa3e8672',
        'SourceName': 'gh_5b0c2f762fc0@app',
        'Icon': 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM5bBMPvk6Oohdlo4FpjGgLsTtcSYJKhibnoQWFphTVy7Bw/96',
        'Source': '建业+',
        'Title': '考拉之选 点断保鲜膜 食品级材质',
        'Thumb': 'http://gaia-projectc.oss-cn-hangzhou.aliyuncs.com/wxid_9988ti1oz81g22%2Fth_2fb4cbd7008c2e3cc33f6e49573c00cc.jpg',
        'PagePath': 'pages/index/index.html?_type=h5Link&h5url=https%3A%2F%2Fmall.yijiahn.com%2Fmall%2Fapp%2Fstatic%2Fgoods%2F3711147.html%3Fid%3D3711147&sharedUserId=2269485',
        // 'Des': '',
      },
      weappRules: {
        AppId: [
          { required: true, message: '请输入AppId', trigger: 'blur' },
        ],
        SourceName: [
          { required: true, message: '请输入SourceName', trigger: 'blur' },
        ],
        Icon: [
          { required: true, message: '请输入Icon', trigger: 'blur' },
        ],
        PagePath: [
          { required: true, message: '请输入PagePath', trigger: 'blur' },
        ],
        // Source: [
        //   { required: true, message: '请输入Source', trigger: 'blur' },
        // ],
        Title: [
          { required: true, message: '请输入Title', trigger: 'blur' },
        ],
        Thumb: [
          { required: true, message: '请输入Thumb', trigger: 'blur' },
        ],
      },
      linkForm: {
        "Title": "“关闭领馆”落下帷幕! 外媒: 他们不再含泪抗议, 而是在大使馆前笑着合影",
        "Thumb": "http://www.jjldkj.com/files/phone/files/20200730/935FC7F27A771E914BD47DC261385309.jpg",
        "Url": "https://iflow.uc.cn/webview/news?app=meitullq-iflow&aid=17561738358438069514&cid=100&zzd_from=meitullq-iflow&uc_param_str=dndsfrvesvntnwpfgibicp&recoid=2043722754382504392&rd_type=reco&sp_gz=0&activity=1&activity2=1&dn=cf9807c357d1e8561c9aef3f75f05e71&enuid=AAPTn90AUlH8qpsGXMgpzgD%2BzWybOCOjkJX%2B2Ou9k8Lrzg%3D%3D&uc_iflow_biz=cmt%3A1&imei=bTkwAA3esoPsTi%2Ff%2FLrBSXG9zpdQ2YF7sw%3D%3D",
        "Des": "震惊Des",
        "TypeStr": "[链接]",
      },
      linkRules: {
        Title: [
          { required: true, message: '请输入Title', trigger: 'blur' },
        ],
        Thumb: [
          { required: true, message: '请输入Thumb', trigger: 'blur' },
        ],
        Url: [
          { required: true, message: '请输入Url', trigger: 'blur' },
        ],
        Des: [
          { required: true, message: '请输入Des', trigger: 'blur' },
        ],
      },

      tags: [], // 标签
      search: '', // 搜索框的内容
      searchContent: [], // 搜索结果
      dialogSearchVisible: false, // 显示搜索的结果
      timeOut: 10, // 群发间隔 分
      sending: false, // 发送状态
      friendIdChose: [], // 要发送的好友/群id
      //   type: 'Text', // 群发类型
      //   content: '', // 文本内容

      // 好友筛选用到的数据
      wechat2send: '', // 要发送的微信
      friends2send: [], // 选中的好友
      team2screen: '', // 要筛选的分组 暂时用不到
      state2screen: '', // 要筛选的状态 暂时用不到
      gender2screen: '', // 要筛选的性别
      lableRadio: 'inclusion', // 标签 包含inclusion,不包含exclude
      labels2screen: [], // 要筛选的标签
      cities: [], // 要筛选的城市
      city2screen: [], // 要筛选的城市
      // 群筛选用到的数据
      wechat2send2room: '', // 要发送的群
      rooms2send: [], // 选中的群
      room2screen: '', // 要筛选的群
      currentStep: 0, // 当前步骤
      currentStepStatus: 'process', // 当前步骤的状态 wait / process / finish / error / success
      cityRadio: 'inclusion', // 城市 包含inclusion,不包含exclude
      // 信息展示用到的数据
      tableDataFriends: [], // 表格中的数据
      totalFriends: 0, // 总的好友
      tableDataRooms: [], // 群聊表格中的数据
      totalRooms: 0, // 总的群聊
      // 性别
      gender: [
        {
          value: 'Male',
          label: '男'
        },
        {
          value: 'Female',
          label: '女'
        }
      ],
      ids2send: [], // 要发送的好友/群id
    }
  },
  computed: {
    ...mapGetters({
      // currentNavs: 'currentNavs',
      // currentWechats: 'currentWechats',
      wechats: 'conversation/wechats',
      groupSendRooms: 'nedb/groupSendRooms',
      groupSendLabels: 'nedb/groupSendLabels',
      groupSendFriends: 'nedb/groupSendFriends',
      // wechatsLogin: 'conversation/wechatsLogin',
    }),
    // 中国城市数据
    chineseCities() {
      let cities = []
      for (const cityList of chineseCities) {
        let cityChildren = []
        for (const cityName of cityList.list) {
          cityChildren.push({
            value: cityName,
            label: cityName,
          })
        }
        cities.push({
          value: cityList.letter,
          label: cityList.letter,
          children: cityChildren
        })
      }
      return cities
    },
    // 信息总数
    totalNum() {
      if (this.activeTabName === "choseFriends") {
        return this.totalFriends
      } else if (this.activeTabName === "choseRooms") {
        return this.totalRooms
      } else {
        return 0
      }
    },
    // 表格中的数据
    tableData() {
      //   if (this.activeTabName === "choseFriends") {
      //     return this.tableDataFriends
      //   }
      //   return this.tableDataRooms
      // 筛选出来的好友进行分组
      let size = this.pageSize
      let newFriends = []
      if (this.activeTabName === "choseFriends") {
        for (let i = 0; i < this.tableDataFriends.length; i += size) {
          newFriends.push(this.tableDataFriends.slice(i, i + size))
        }
      } else {
        for (let i = 0; i < this.tableDataRooms.length; i += size) {
          newFriends.push(this.tableDataRooms.slice(i, i + size))
        }
      }
      return newFriends
    },
    // 搜索结果是否全选
    // allCheckState() {
    //   let state = this.searchContent.every((x) => {
    //     return this.friendIdChose.indexOf(x.FriendId) >= 0
    //   })
    //   return state
    // },
  },
  methods: {
    // 根据微信id查询数据
    queryInfoByWechatId() {
      if (this.activeTabName === 'choseFriends' && this.wechat2send) {
        this.tableDataFriends = []
        // 查询当前微信的标签
        this.$store.dispatch('nedb/SetGroupSendLabels', this.wechat2send)
        // 查询当前微信的好友
        this.$store.dispatch('nedb/SetGroupSendFriends', this.wechat2send)
      } else if (this.activeTabName === 'choseRooms' && this.wechat2send2room) {
        this.tableDataRooms = []
        // 查询当前微信的群聊
        this.$store.dispatch('nedb/SetGroupSendRooms', this.wechat2send2room)
      }
    },
    // 选择城市
    handleCityChange(value) {
      if (value.length === 0) return
      let nc = []
      for (const item of value) {
        nc.push(item[1])
      }
      this.city2screen = nc
    },
    // 筛选好友
    screenFriends() {
      // 如果没有选择微信 则不做处理
      if (!this.wechat2send) {
        this.$message.warning('请选择微信！')
        return
      }
      let friendsFiltered = []
      // 默认显示全部的好友
      for (const friend of this.groupSendFriends) {
        friendsFiltered.push(friend)
      }
      // 如果要筛选性别
      if (this.gender2screen) {
        friendsFiltered = friendsFiltered.filter((currentValue, index, arr) => {
          return currentValue.Gender === this.gender2screen
        })
      }
      // 如果要筛选标签
      if (this.labels2screen.length > 0) {
        let nfl = []
        for (const iterator of friendsFiltered) {
          let currentLabelIds = []
          if (iterator.LabelIds) {
            currentLabelIds = iterator.LabelIds.replace('"', '[').replace('"', ']').split(',')
          }
          // 交集
          let intersection = this.labels2screen.filter(function (val) { return currentLabelIds.indexOf(val.toString()) > -1 })
          // 是包含还是不包含
          if (this.lableRadio === 'inclusion' && intersection.length > 0) {
            nfl.push(iterator)
          } else if (this.lableRadio === 'exclude' && intersection.length === 0) {
            nfl.push(iterator)
          }
        }
        friendsFiltered = nfl
      }
      // 如果要筛选城市
      if (this.city2screen.length > 0) {
        let nfc = []
        for (const iterator of friendsFiltered) {
          let currentCity = iterator.City ? iterator.City : ''
          // 是包含还是不包含
          if (this.cityRadio === 'inclusion' && this.city2screen.indexOf(currentCity) > -1) {
            nfc.push(iterator)
          } else if (this.cityRadio === 'exclude' && this.city2screen.indexOf(currentCity) === -1) {
            nfc.push(iterator)
          }
        }
        friendsFiltered = nfc
      }
      // 筛选出来的好友进行分组
      //   let size = this.pageSize
      //   let newFriends = []
      //   for (let i = 0; i < friendsFiltered.length; i += size) {
      //     newFriends.push(friendsFiltered.slice(i, i + size))
      //   }
      this.totalFriends = friendsFiltered.length
      //   this.tableDataFriends = newFriends
      this.tableDataFriends = friendsFiltered
    },
    // 筛选群聊
    screenRooms() {
      // 如果没有选择微信 则不做处理
      if (!this.wechat2send2room) {
        this.$message.warning('请选择微信！')
        return
      }
      let roomsFiltered = []
      // 默认显示全部的好友
      for (const room of this.groupSendRooms) {
        roomsFiltered.push(room)
      }
      if (this.room2screen) {
        let nr = []
        for (const room of roomsFiltered) {
          if (room.NickName.indexOf(this.room2screen) > -1) {
            nr.push(room)
          }
        }
        roomsFiltered = nr
      }
      // 筛选出来的好友进行分组
      //   let size = this.pageSize
      //   let newRooms = []
      //   for (let i = 0; i < roomsFiltered.length; i += size) {
      //     newRooms.push(roomsFiltered.slice(i, i + size))
      //   }
      this.totalRooms = roomsFiltered.length
      //   this.tableDataRooms = newRooms
      this.tableDataRooms = roomsFiltered
    },
    // 重置
    resetFilter() {
      if (this.activeTabName === 'choseFriends') {
        this.wechat2send = ""
        this.gender2screen = ""
        this.lableRadio = "inclusion"
        this.labels2screen = []
        this.cities = []
        this.cityRadio = "inclusion"
        this.city2screen = []
        this.tableDataFriends = []
      } else {
        this.wechat2send2room = ""
        this.room2screen = ''
        this.tableDataRooms = []
      }
    },
    // 计算序号
    indexMethod(index) {
      return index + 1;
    },
    // 选择row
    choseRow(row) {
      // 好友
      if (this.activeTabName === 'choseFriends') {
        let friendId = row.FriendId
        let fid = this.friends2send.indexOf(friendId)
        fid >= 0 ? this.friends2send.splice(fid, 1) : this.friends2send.push(friendId)
      } else {
        // 群聊
        let roomId = row.UserName
        let rid = this.rooms2send.indexOf(roomId)
        rid >= 0 ? this.rooms2send.splice(rid, 1) : this.rooms2send.push(roomId)
      }
    },
    // 该row是否被选中
    computedCheckState(row) {
      if (this.activeTabName === 'choseFriends') {
        return this.friends2send.indexOf(row.FriendId) >= 0
      }
      return this.rooms2send.indexOf(row.UserName) >= 0
    },
    // 本页全选
    choseAllOfPage() {
      let rows = this.tableData[this.currentPage[this.activeTabName] - 1]
      if (this.activeTabName === 'choseFriends') {
        let rowsArry = rows.map((x) => x.FriendId)
        let intersection = this.friends2send.filter(function (val) { return rowsArry.indexOf(val) > -1 })
        if (intersection.length === rowsArry.length) {
          for (const row of rows) {
            let friendId = row.FriendId
            let fid = this.friends2send.indexOf(friendId)
            this.friends2send.splice(fid, 1)
          }
        } else {
          for (const row of rows) {
            let friendId = row.FriendId
            let fid = this.friends2send.indexOf(friendId)
            if (fid < 0) {
              this.friends2send.push(friendId)
            }
          }
        }
      } else {
        let rowsArry = rows.map((x) => x.UserName)
        let intersection = this.rooms2send.filter(function (val) { return rowsArry.indexOf(val) > -1 })
        if (intersection.length === rowsArry.length) {
          for (const row of rows) {
            let roomId = row.UserName
            let rid = this.rooms2send.indexOf(roomId)
            this.rooms2send.splice(rid, 1)
          }
        } else {
          for (const row of rows) {
            let roomId = row.UserName
            let rid = this.rooms2send.indexOf(roomId)
            if (rid < 0) {
              this.rooms2send.push(roomId)
            }
          }
        }
      }
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage[this.activeTabName] = val
    },
    // 添加消息
    addContent(msgType) {
      let newContent = {
        msgType: this.msgType,
      }
      // msgContent: this.msgContent
      switch (msgType) {
        case 'Text':
        case 'Picture':
        case 'Voice':
        case 'Video':
          newContent.msgContent = this.msgContent
          break;
        case 'Link':
          //   newContent.msgContent = this.linkForm
          this.$refs['linkDialog'].validate((valid) => {
            if (valid) {
              newContent.msgContent = JSON.stringify(this.linkForm)
            } else {
              return false;
            }
          });
          break;
        case 'WeApp':
          this.$refs['weappDialog'].validate((valid) => {
            if (valid) {
              newContent.msgContent = JSON.stringify(this.weapp)
            } else {
              return false;
            }
          });
          break;
        default:
          break;
      }
      this.contentData.push(newContent)
      this.showContentDialog = false
      this.msgType = 'Text'
      this.msgContent = ''
      this.hideUpload = false
      this.showFileList = true
    },
    // 重置表单
    resetForm(msgType) {
      if (msgType === "Link") {
        this.$refs['linkDialog'].resetFields();
      } else {
        this.$refs['weappDialog'].resetFields();
      }
    },
    // 文件改变
    handleImageChange(file, fileList) {
      if (fileList.length > 0) {
        this.showFileList = true
        this.hideUpload = true
      }
    },
    // 文件类型大小验证
    beforeImageUpload(file) {
      // 图片
      if (this.msgType === 'Picture') {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.warning('上传头像图片只能是 JPG|PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.warning('上传头像图片大小不能超过 2MB!')
        }
        this.upData.myfile = file
        return isJPG && isLt2M;
      } else if (this.msgType === 'Video') {
        const isMP4 = file.type === 'video/mp4'
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isMP4) {
          this.$message.warning('上传视频只能是 MP4 格式!')
        }
        if (!isLt10M) {
          this.$message.warning('上传视频大小不能超过 10MB!')
        }
        this.upData.myfile = file
        return isMP4 && isLt10M
      } else if (this.msgType === 'Voice') {
        let fileType = file.name.replace(/.+\./, '').toLowerCase()
        const isAudio = fileType === 'mp3' || fileType === 'amr'
        // const isAudio = file.type === 'audio/mpeg' || ''
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isAudio) {
          this.$message.warning('上传语音只能是 MP3或AMR 格式!')
          return
        }
        if (!isLt10M) {
          this.$message.warning('上传语音大小不能超过 10MB!')
          return
        }
        if (fileType === 'mp3') {
          this.upData.isMp3ToAmr = true
        } else if (fileType === 'amr') {
          this.upData.isAmrToMp3 = false
        }
        this.upData.myfile = file
        return isAudio && isLt10M
      }
    },
    // 文件上传成功
    handleImageSuccess(res, file) {
      this.msgContent = res.data.url;
      // 隐藏添加的按钮
      //   let upload_div = document.getElementsByClassName('el-upload--picture-card')[0];
      //   upload_div.style.cssText = "display: none;";//设置目标element的style内容
    },
    // 文件上传失败
    handleImageError(err, file) {
      this.$alert(err, '文件上传失败', { type: 'error' })
      this.hideUpload = false
    },
    // 文件移除
    handleRemove(file, fileList) {
      this.msgContent = ''
      this.showFileList = false
      this.hideUpload = false
      // 显示添加的按钮
      //   let upload_div = document.getElementsByClassName('el-upload--picture-card')[0];
      //   upload_div.style.cssText = "";
    },
    // 图片展示
    handlePictureCardPreview(file) {
      //   this.imageUrl = file.url;
      this.dialogVisible = true;
    },
    // 消息上移
    removeUp(index) {
      let array = this.contentData
      let index2 = index - 1
      // splice() 方法会直接对数组进行修改,splice() 方法向/从数组中添加/删除项目，然后返回被删除的项目
      array.splice(index2, 1, ...array.splice(index, 1, array[index2]));
    },
    // 消息下移
    removeDown(index) {
      let array = this.contentData
      let index2 = index + 1
      array.splice(index2, 1, ...array.splice(index, 1, array[index2]));
    },
    // 删除消息
    deleteContent(index) {
      this.contentData.splice(index, 1)
    },
    // 群发全部/群发所选
    sendNext(flag) {
      let ids = []
      if (flag === 'all') {
        if (this.activeTabName === 'choseFriends') {
          ids = this.tableDataFriends.map((val) => {
            return val.FriendId
          })
        } else {
          ids = this.tableDataRooms.map((val) => {
            return val.UserName
          })
        }
      } else {
        if (this.activeTabName === 'choseFriends') {
          ids = this.friends2send
        } else {
          ids = this.rooms2send
        }
      }
      if (ids.length > 0) {
        this.ids2send = ids
        this.currentStep = 1
      } else {
        this.$message.warning('请先选择要发送的好友！')
      }
    },
    // 定时群发 时间转换
    transformTime(times) {
      var date = new Date(times)
      let Y = date.getFullYear() + '-'
      let M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      // let s = date.getSeconds()
      let time = Y + M + D + h + m
      return time
    },
    // 定时发送
    sendTimer(tt, content) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        this.$store.dispatch('websocket/AddTaskTimeInfo', content)
        if ((tt + 1) === Math.ceil(this.friendIdChose.length / 200)) {
          loading.close();
        }
      }, 500 * tt);
    },
    // 确认群发 立即发送和定时任务 都是走的定时发送接口
    sureSend() {
      // 没有内容不能发送
      if (this.contentData.length === 0) {
        this.$message.warning('请设置群发内容！')
        return
      }

      // 发送的起始时间
      let startTime = new Date().getTime()
      if (this.timeRadio === 'timing') {
        startTime = this.refTime
      }
      // 目前只支持文字和图片
      let typeMap = {
        "Text": 1,
        "Picture": 2,
        "Voice": 3,
        "Video": 4,
        "Link": 6,
        "WeApp": 13,
      }
      // 遍历内容
      let tb = 0
      for (const content of this.contentData) {
        // 是文字或图片
        if (typeMap[content.msgType]) {
          let execute_time = startTime + 130 * 1000 * tb
          let message = {
            tasktype: this.activeTabName === 'choseFriends' ? 1 : 5, // 1:群发好友 5:群发群
            state: 1, // 状态1开启中0已完成
            wechatId: this.activeTabName === 'choseFriends' ? this.wechat2send : this.wechat2send2room, // 要执行的微信号
            // wechatList: this.friends2send, // 好友的微信号
            wechatList: this.activeTabName === 'choseFriends' ? this.friends2send : this.rooms2send, // 好友的微信号
            execute_time: this.transformTime(execute_time), // 执行时间
            restype: typeMap[content.msgType], // 资源类型(群发好友:0文字 1图片；朋友圈:0链接 2图片 3短视频)
            content: content.msgContent, // 内容
          }
          this.$store.dispatch('websocket/AddTaskTimeInfo', message)
        }
        tb++
      }
      this.$message.success('群发好友任务,已经下发!')
    },
    // =====================================================================
    // formatLabelId(LabelIds) {
    //   let labelIds = []
    //   if (LabelIds) {
    //     labelIds = LabelIds.split(',')
    //   }
    //   return labelIds
    // },
    // 搜索
    // searchChange() {
    //   let newFriends = []
    //   let val = this.search
    //   if (!val) return
    //   for (const friend of this.groupSendFriends) {
    //     if ((friend.FriendNick && friend.FriendNick.indexOf(val) >= 0) || (friend.Memo && friend.Memo.indexOf(val) >= 0)) {
    //       newFriends.push(friend)
    //     }
    //   }
    //   this.searchContent = newFriends
    //   this.dialogSearchVisible = true
    // },
    // 显示labels
    // showLabel(label) {
    //   let labelId = label.LabelId.toString()
    //   let newFriends = []
    //   for (const friend of this.groupSendFriends) {
    //     if (friend.LabelIds) {
    //       let la = friend.LabelIds.split(',')
    //       if (la.indexOf(labelId) >= 0) {
    //         newFriends.push(friend)
    //       }
    //     }
    //   }
    //   if (newFriends.length > 0) {
    //     this.searchContent = newFriends
    //     this.dialogSearchVisible = true
    //   } else {
    //     this.$message.warning('没有数据')
    //   }
    // },
    // 关闭searchdialog 之前先清空数据
    // closeDialog(done) {
    //   this.searchContent = []
    //   done()
    // },
    // 搜索内容全选
    // choseAllSearchContent() {
    //   if (this.allCheckState) {
    //     for (const friend of this.searchContent) {
    //       let friendId = friend.FriendId
    //       let fid = this.friendIdChose.indexOf(friendId)
    //       this.friendIdChose.splice(fid, 1)
    //     }
    //   } else {
    //     for (const friend of this.searchContent) {
    //       let friendId = friend.FriendId
    //       let fid = this.friendIdChose.indexOf(friendId)
    //       if (fid < 0) {
    //         this.friendIdChose.push(friendId)
    //       }
    //     }
    //   }
    // },
  }
}
</script>

<style lang="scss" scoped>
.group-assistant-send {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: space-between;
  //   border: solid red 1px;

  ::v-deep .group-send-steps {
    // border-bottom: $border-color-1 solid 2px;
    .el-step__icon {
      .el-step__icon-inner {
        font-size: 24px;
      }
    }
    .el-step__main {
      .el-step__title {
        font-size: 14px;
        font-weight: 300px;
      }
    }
  }

  .group-send-content {
    flex: 1 1 auto;
    border-bottom: $border-color-1 solid 2px;
    padding: 5px;
    overflow: hidden;

    .chose-friend {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      overflow: hidden;

      ::v-deep .chose-friend-left {
        overflow: hidden;
        width: 48%;
        display: flex;
        flex-direction: column;
        .el-tabs__header {
          .el-tabs__item {
            height: 50px;
            line-height: 50px;
            @include can-not-select;
          }
        }
        .el-tabs__content {
          flex: 1 1 auto;
          padding: 0;
          overflow: hidden;
          .el-tab-pane {
            height: 100%;
            overflow: auto;
            @include scroll;
            .el-tab-pane-item {
              display: flex;
              align-items: center;
              padding: 10px;
              .el-input {
                width: 250px;
              }
              .el-tab-pane-item-title {
                width: 80px;
                text-align: end;
                display: inline-block;
                margin-right: 15px;
              }
              .el-radio-group {
                padding: 5px;
              }
            }
            .el-tab-pane-btns {
              text-align: center;
              margin-left: 80px;
            }
          }
        }
      }

      .chose-friend-right {
        width: 48%;
        height: 100%;
        display: flex;
        flex-direction: column;
        border: solid #dcdfe6 1px;
        ::v-deep .el-table {
          .el-table__header-wrapper {
            height: 50px;
            // border: solid red 1px;
            // .el-table__header {
            //   height: 50px;
            // }
          }
        }
        .el-pagination {
          margin: 5px 0;
          align-self: center;
        }
      }
    }

    .set-send-content {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      .add-new-msg-btn {
        width: 100px;
        margin-bottom: 5px;
      }
      .set-time {
        //   border: solid red 1px;
        margin: 5px 0;
        font-size: 14px;
        color: $font-color-2;
        .broke-time {
          padding: 5px 0;
        }
      }
    }
  }

  .group-send-operation {
    width: 100%;
    // padding: 5px;
    padding: 7px 15px 5px;
    // margin-right: 15px;
    display: flex;
    justify-content: flex-end;
    // border: solid red 1px;
  }

  .el-dialog-content {
    ::v-deep .el-dialog {
      width: 500px;
    }
    .set-type {
      display: flex;
      align-items: center;

      .set-type-span {
        width: 110px;
        // text-align: end;
        padding-right: 12px;
        font-weight: bold;
      }
    }
    .set-content {
      margin: 20px 0 5px 0;
      display: flex;
      flex-direction: column;
      align-items: center;

      ::v-deep .hide .el-upload--picture-card {
        display: none;
      }
      .we-app {
        width: 100%;
      }
    }
    .tips {
      color: #f5a623;
      margin-top: 10px;
    }
  }
}
</style>
